import { ifLoggerKeeper } from "./base";
import { HashMap, Util } from "../lib/Util";
import { LocalDate } from "../lib/Time";
import { http_quest } from "../lib/HttpQuest";
import path from "path";

export type TGAParams = { path: string }

// 这个是提供给特殊情况下的tga使用的，在聚石塔的容器服务中部署，日志记录不能以本地文件的形式落地，这样收集会很复杂，这里提供一个中转接收落地的策略
export class TGALoggerNet implements ifLoggerKeeper {
    private _catch: HashMap<any> = new HashMap();
    private handle: { stop: any; } | undefined;
    private path: string = "";
    name = "tga"
    constructor(cfg: { path: string }) {
        this.path = cfg.path;
        if (!this.path) console.error("path is empty")
    }

    async init() {
        if (this.handle) this.handle.stop();
        this.handle = Util.setInterval(this.update.bind(this), 2000);
        return true
    }

    private async update() {
        if (!this.path) {
            this._catch.clear();
            return;
        }
        // this.mkdirsSync(this.path);

        let keys = this._catch.keys;
        for (let j = 0; j < keys.length; j++) {
            let time = new LocalDate;
            // 日志按照小时记录在文件中
            let logName = `${process.pid}-${time.getFullYear()}-${time.getMonth() + 1}-${time.getDate()}_${time.getHours()}.tga.log`
            let fileName = logName;
            let write_buff = '';
            let cache = this._catch.get(keys[j]);
            for (let i = 0; i < cache.length; i++) {
                write_buff += JSON.stringify(cache[i], function (k, v) {
                    if (typeof v == 'string') {
                        v = v.replace(/"/g, '\\"');
                    }
                    return v;
                }) + '\n';
                if (i != 0 && i % 20 == 0) {
                    http_quest("post", this.path, { file: fileName, data: write_buff })
                    write_buff = '';
                }
            }
            if (write_buff.length != 0) {
                http_quest("post", this.path, { file: fileName, data: write_buff })
                write_buff = '';
            }
        }

        this._catch.clear();
        return;
    }

    logEvent(uid: string, event_name: string, obj: Object) {
        let s = {
            "#account_id": (uid || "").toString(),
            // "#distinct_id": "F53A58ED-E5DA-4F18-B082-7E1228746E88",
            "#type": 'track',
            // "#ip": "192.168.171.111",
            // "#time": "2017-12-18 14:37:28.527",
            "#time": /*"2017-12-18 14:37:28.527"*/ LocalDate.formateString(Date.now()),
            "#event_name": event_name,
            "properties": obj
        }

        this._catch.add(event_name, s);
    }

    logStatic(uid: string, eventType: string, obj: Object) {
        let account_id = (uid || "").toString();
        let s = {
            "#account_id": account_id,
            // "#distinct_id": "F53A58ED-E5DA-4F18-B082-7E1228746E88",
            "#type": (eventType || "").toString(),
            // "#ip": "192.168.171.111",
            "#time": /*"2017-12-18 14:37:28.527"*/ LocalDate.formateString(Date.now()),
            "properties": obj
        }

        this._catch.add('_static_', s);
    }

    logApi(api: string, method: string, uid: string, succ: boolean, consumeTime: number, reqID: string, param: string, response: string) {
        let event_name = "api";
        let s = {
            "#account_id": (uid || "").toString(),
            // "#distinct_id": "F53A58ED-E5DA-4F18-B082-7E1228746E88",
            "#type": 'track',
            // "#ip": "192.168.171.111",
            // "#time": "2017-12-18 14:37:28.527",
            "#time": /*"2017-12-18 14:37:28.527"*/ LocalDate.formateString(Date.now()),
            "#event_name": event_name,
            "properties": {
                'api_category': api,
                'api_method': method,
                'is_success': succ ? 1 : 0, // 1成功 0失败
                'consume_time': consumeTime, // 耗时 15毫秒
                'user_from': (uid || "null").toString(),
                'user_identify': (reqID || "null").toString(), // 记录标识  可以是订单号
                'api_response': response.slice(0, 300), // 只显示前100个字符试试
                'api_param': param.slice(0, 300), // 只显示前100个字符试试
            }
        }

        // this._catch.add(event_name, s);
    }
}